import {parse} from 'qs'
import modelExtend from 'dva-model-extend'
import * as reportConfigService from 'services/reportConfig'

import { request, config } from 'utils'
const { defaultPageSize } = config
const model = {
  reducers: {
      updateState(state, { payload }) {
          return {
              ...state,
              ...payload
          }
      }
  }
}
const lwjPageModel = modelExtend(model, {

  state: {
      items: [],
      pagination: {
          current: 1,
          total: 0,
          showTotal: total => `共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: defaultPageSize
      }
  },

  reducers: {
      querySuccess(state, { payload }) {
          // console.log(`querySuccess payload: ${JSON.stringify(payload)}`); const
          // {items, pagination} = payload; console.log(`items payload:
          // ${JSON.stringify(items)}`); console.log(`pagination payload:
          // ${JSON.stringify(pagination)}`);
          return {
              ...state,
              items: payload.items,
              pagination: {
                  ...state.pagination,
                  current: payload.page,
                  total: payload.totalCount
              }
          }
      }
  }
})

export default modelExtend(lwjPageModel, {
  namespace: 'reportConfig',
  state: {
    currentItem: {},
    selectedRowKeys: [],
    selectedRows: [],
    selectedRows: [],
    modalDetailVisible: false,
    modalVisible: false,
    modalType: 'create',
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      history.listen(({pathname}) => {
        if (pathname === '/reportConfigs' || pathname === '/') {
          dispatch({type: 'query', payload: {}})
        }
      })
    }
  },
  effects: {
    * query({
      payload
    }, {select, call, put}) {
      const pageOptions = yield select(({reportConfig}) => reportConfig.pageOptions);
      const queryPayload = {
        ...pageOptions,
        queryParam: {
          ...payload
        }
      }
      const data = yield call(reportConfigService.query, queryPayload);
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },

    * create({
      payload
    }, {call, put}) {
      const data = yield call(reportConfigService.create, payload)
      if (data.success) {
        yield put({type: 'hideModal'})
        yield put({type: 'query'})
      } else {
        throw data
      }
    },

    * update({
      payload
    }, {select, call, put}) {
      const id = yield select(({reportConfig}) => reportConfig.currentItem.id)
      const config4Update = {
        ...payload,
        id
      }
      const data = yield call(reportConfigService.update, config4Update)
      if (data.success) {
        yield put({type: 'hideModal'})
        yield put({type: 'query'})
      } else {
        throw data
      }
    },

    * delete({
      payload
    }, {call, put}) {
      const {currentItem} = payload;
      console.log(`deleted:${currentItem.id}`);
      const data = yield call(reportConfigService.deleteBy, currentItem.id, currentItem.version);
      if (data) {
        yield put({type: 'query'})
      }
    },

    * showDetail({
      payload
    }, {call, put}) {
      const {currentItem} = payload;
      const grantedIds = yield call(reportConfigService.getGrantIdsBy, currentItem.id);
      currentItem.grantedIds = grantedIds;
      yield put({
        type: 'showModalDetail',
        payload: {
          currentItem: currentItem
        }
      });
    },

    * detail({
      payload
    }, {call, put}) {
      let {currentItem} = payload;
      const itemDetail = yield call(reportConfigService.detail, currentItem.id);
      if (typeof itemDetail.queryParamJson == 'string') {
        itemDetail.queryParamJson = JSON.parse(itemDetail.queryParamJson);
      }
      // 处理数据来源系统
      itemDetail.reportDataFromSys = itemDetail.reportDataFromSys + "";
      // 处理地区
      itemDetail.area = ["710000"];
      // 为每一个查询条件，增加一个index
      if (itemDetail.queryParamJson) {
        var index = 1;
        for (var paramJson of itemDetail.queryParamJson) {
          var defaultCheckValue = [];
          paramJson.index = index;
          // paramJson.testname = paramJson.name;
          if (paramJson.isRequired) {
            defaultCheckValue.push("isRequired");
          }
          if (paramJson.isLike) {
            defaultCheckValue.push("isLike");
          }
          if (paramJson.isDayEndTime) {
            defaultCheckValue.push("isDayEndTime");
          }
          paramJson.defaultCheckValue = defaultCheckValue;
          index++;
        }
      }
      currentItem = itemDetail;
      yield put({
        type: 'showModal',
        payload: {
          ...payload,
          currentItem: currentItem
        }
      });
    }
  },
  reducers: {
    showModalDetail(state, {payload}) {
      return {
        ...state,
        ...payload,
        modalDetailVisible: true
      }
    },

    showModal(state, {payload}) {
      return {
        ...state,
        ...payload,
        modalVisible: true
      }
    },

    hideModal(state) {
      return {
        ...state,
        modalVisible: false,
        modalDetailVisible: false
      }
    },

    addParam(state, {payload}) {
      return {
        ...state,
        ...payload
      }
    },

    deleteParam(state, {payload}) {
      return {
        ...state,
        ...payload
      }
    },

    changeParams(state, {payload}) {
      return {
        ...state,
        ...payload
      }
    },

    updateSelectedRows(state, {payload}) {
      return {
        ...state,
        ...payload
      }
    },

    setFormDirty(state, {payload}) {
      return {
        ...state,
        ...payload,
        isFormDirty: payload.isFormDirty
      }
    }
  }
})
